// import EllipsisBox from '@/page-components/EllipsisBox/idnex';
import services from '@/services/demo';
import {
  ActionType,
  FooterToolbar,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Divider, Drawer, message } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import UpdateForm, { FormValueType } from './components/UpdateForm';
const { deleteUser, modifyUser, getEmergencyList } = services.UserController;

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在配置');
  try {
    await modifyUser(
      {
        userId: fields.id || '',
      },
      {
        name: fields.name || '',
        nickName: fields.nickName || '',
        email: fields.email || '',
      },
    );
    hide();

    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.UserInfo[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await deleteUser({
      userId: selectedRows.find((row) => row.id)?.id || '',
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<unknown> = () => {
  const { name } = useModel('global');
  console.log(name);
  const [updateModalVisible, handleUpdateModalVisible] =
    useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.UserInfo>();
  const [selectedRowsState, setSelectedRows] = useState<API.UserInfo[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const columns = [
    {
      title: '隐患编号',
      dataIndex: 'code',
      width: 80,
    },
    {
      title: '所属',
      dataIndex: 'deptName',
      width: 80,
    },
    {
      title: '发现时间',
      dataIndex: 'findTime',
      render: (_: string | number, record: any) => {
        return <div>{_ ? dayjs(+_).format('YYYY-MM-DD') : ''}</div>;
      },
      width: 80,
    },
    {
      title: '整改时间',
      dataIndex: 'correctionTime',
      render: (_: string | number, record: any) => {
        return typeof _ === 'number' ? (
          <div>{_ ? dayjs(+_).format('YYYY-MM-DD') : ''}</div>
        ) : (
          '-'
        );
      },
      width: 80,
    },
    {
      title: '措施验证时间',
      dataIndex: 'checkTime',
      render: (_: any[], record: any) => {
        if (Array.isArray(_)) {
          let text = _.map((item) => dayjs(+item).format('YYYY-MM-DD')).join(
            '、',
          );
          return text;
        }
        return '-';
      },
      width: 80,
    },
    {
      title: '是否关闭',
      dataIndex: 'status',
      render: (_: string, record: any) => <div>{_ === '3' ? '是' : '否'}</div>,
      width: 80,
    },
    {
      title: '关闭时间',
      dataIndex: 'closeTime',
      render: (_: string | number, record: any) => {
        return typeof _ === 'number' ? (
          <div>{_ ? dayjs(+_).format('YYYY-MM-DD') : ''}</div>
        ) : (
          '-'
        );
      },
      width: 80,
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      render: (
        _: string | number | Date | dayjs.Dayjs | null | undefined,
        record: any,
      ) => {
        return _ ? dayjs(_).format('YYYY-MM-DD HH:mm:ss') : '-';
      },
      width: 90,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_: any) => _,
      // <Tag
      //   color={getItemValueFromOptions(
      //     StatusOptions,
      //     record?.status,
      //     'color',
      //   )}
      // >
      //   {getItemValueFromOptions(StatusOptions, record?.status)}
      // </Tag>
      width: 80,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: '100px',
      render: (_: any, record: React.SetStateAction<{}>) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            配置
          </a>
          <Divider type="vertical" />
          <a href="">订阅警报</a>
        </>
      ),
    },
  ] as any[];

  useEffect(() => {
    getEmergencyList({
      pageSize: 20,
      pageNum: 1,
      timeType: 'DAY',
      deviceType: 'ELECTRICITY',
    }).then((res) => {
      if (res?.code === 200) {
        setDataSource(res?.data?.records);
      }
    });
  }, []);

  return (
    <>
      <ProTable<API.UserInfo>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button key="1" type="primary">
            新建
          </Button>,
        ]}
        dataSource={dataSource}
        columns={columns as any}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        pagination={{
          pageSize: 20,
        }}
        scroll={{ x: 1500 }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}

      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}

      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions<API.UserInfo>
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </>
  );
};

export default TableList;
